/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.zouqone.smc.modules.sys.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zouqone.smc.common.config.Global;
import com.zouqone.smc.common.persistence.Page;
import com.zouqone.smc.common.utils.StringUtils;
import com.zouqone.smc.common.web.BaseController;
import com.zouqone.smc.modules.sys.entity.Dict;
import com.zouqone.smc.modules.sys.entity.Dictitem;
import com.zouqone.smc.modules.sys.service.DictService;
import com.zouqone.smc.modules.sys.service.DictitemService;

/**
 * 字典Controller
 * @author ThinkGem
 * @version 2014-05-16
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/dict")
public class DictController extends BaseController {

	@Autowired
	private DictService dictService;
	
	@Autowired
	private DictitemService dictitemService;
	
	@ModelAttribute
	public Dict get(@RequestParam(required=false) String id) {
		if (StringUtils.isNotBlank(id)){
			return dictService.get(id);
		}else{
			return new Dict();
		}
	}
	
	@RequiresPermissions("sys:dict:view")
	@RequestMapping(value = {"list", ""})
	public String list(Dict dict, HttpServletRequest request, HttpServletResponse response, Model model) {
		List<String> typeList = dictService.findTypeList();
		model.addAttribute("typeList", typeList);
		if(!StringUtils.isEmpty(request.getParameter("dict.type"))){
			if(!"100".equals(request.getParameter("dict.type"))){
				dict.setType( request.getParameter("dict.type"));
			}
			Page<Dict> page = dictService.findPage(new Page<Dict>(request, response), dict);
			model.addAttribute("page", page);
		}else if(!StringUtils.isEmpty(request.getParameter("dictitem.id"))){
			String dictitemId = request.getParameter("dictitem.id");
			if(!"100".equals(dictitemId)){
				dict.setParentId(dictitemId);
			}
			Page<Dict> page = dictService.findPageByParentId(new Page<Dict>(request, response), dict);
			model.addAttribute("page", page);
		}else{
			Page<Dict> page = dictService.findPage(new Page<Dict>(request, response), dict);
			model.addAttribute("page", page);
		}
		
		return "modules/sys/dict/dictList";
	}

	@RequiresPermissions("sys:dict:view")
	@RequestMapping(value = "form")
	public String form(Dict dict, Model model) {
		//增加排序号
		if(dict!=null&&StringUtils.isEmpty(dict.getId())&&!StringUtils.isEmpty(dict.getType())){
			String dictType = dict.getType();
			Dict param = new Dict();
			param.setType(dictType);
			List<Dict> list = dictService.findList(param);
			Integer sort = 10;
			if(list != null && list.size() > 0){
				Dict last = list.get(list.size()-1 );
				sort = last.getSort()+10;
			}
			dict.setSort(sort);
		}
		
		model.addAttribute("dict", dict);
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		model.addAttribute("opt",request.getParameter("opt"));
		return "modules/sys/dict/dictForm";
	}
	
	@RequiresPermissions("sys:dict:view")
	@RequestMapping(value = {"index"})
	public String index(Dict dict, Model model) {
		return "modules/sys/dict/dictIndex";
	}
	

	@RequiresPermissions("sys:dict:edit")
	@RequestMapping(value = "save")//@Valid 
	public String save(Dict dict, Model model, RedirectAttributes redirectAttributes) {
		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/sys/dict/?repage&type="+dict.getType();
		}
		if (!beanValidator(model, dict)){
			return form(dict, model);
		}
		dictService.save(dict);
		model.addAttribute("opt","save");
		model.addAttribute("message","保存字典'" + dict.getLabel() + "'成功");
		return "modules/sys/dict/dictForm";
	}
	
	@RequiresPermissions("sys:dict:edit")
	@RequestMapping(value = "delete")
	public String delete(Dict dict, RedirectAttributes redirectAttributes) {
		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/sys/dict/?repage";
		}
		dictService.delete(dict);
		addMessage(redirectAttributes, "删除字典成功");
		return "redirect:" + adminPath + "/sys/dict/?repage&type="+dict.getType();
	}
	
	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(@RequestParam(required=false) String type, HttpServletResponse response) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		Dict dict = new Dict();
		dict.setType(type);
		List<Dict> list = dictService.findList(dict);
		for (int i=0; i<list.size(); i++){
			Dict e = list.get(i);
			Map<String, Object> map = Maps.newHashMap();
			map.put("id", e.getId());
			map.put("pId", e.getParentId());
			map.put("name", StringUtils.replace(e.getLabel(), " ", "")+"  "+(e.getRemarks()==null?"":e.getRemarks()));
			mapList.add(map);
		}
		return mapList;
	}
	
	@ResponseBody
	@RequestMapping(value = "listData")
	public List<Dict> listData(@RequestParam(required=false) String type) {
		Dict dict = new Dict();
		dict.setType(type);
		return dictService.findList(dict);
	}

	/**
	 * 批量修改排序
	 */
	@RequiresPermissions("cms:recommen:edit")
	@RequestMapping(value = "updateSort")
	public String updateSort(String[] ids, Integer[] sorts, RedirectAttributes redirectAttributes) {
    	int len = ids.length;
    	Dict[] entitys = new Dict[len];
    	for (int i = 0; i < len; i++) {
    		entitys[i] = dictService.get(ids[i]);
    		entitys[i].setSort(sorts[i]);
    		dictService.save(entitys[i]);
    	}
    	addMessage(redirectAttributes, "更新顺序成功");
		return "redirect:"+Global.getAdminPath()+"/sys/dict/?repage";
	}
	
	@RequiresPermissions("cms:recommen:edit")
	@ResponseBody
	@RequestMapping(value = "ajaxDelete")
	public Map<String, String> ajaxDelete(String ids,HttpServletRequest request, HttpServletResponse response) {
		Map<String, String> map = new HashMap<String, String>();
		try {
			dictService.delete(ids);
			map.put("message", "删除成功");
			map.put("success", "1");
		} catch (Exception e) {
			// TODO: handle exception
			map.put("message", "删除失败！");
			map.put("success", "0");
			return map;
		}
		return map;
	}
}
